<template>
  <div>
    <editor
      ref="mceEditor"
      :id="id"
      v-model="dataValue"
      v-bind="$attrs"
      :init="showInit"
      :plugins="showPlugins"
      :toolbar="showToolbar"
      tinymce-script-src="https://www.72crm.com/npm/tinymce/tinymce.min.js"
      v-on="$listeners"
    />
    <img id="ceshi" ref="imgId" v-show="false" src alt />
  </div>
</template>

<script>
import Editor from "@tinymce/tinymce-vue";
import QRCode from "qrcodejs2";
import JsBarcode from "jsbarcode";
import plugins from "./plugins";
import toolbar from "./toolbar";

let unique = 0;

export default {
  name: "tsDesignerTinymce",
  components: {
    Editor,
  },
  inheritAttrs: false,
  props: {
    value: String,
    init: Object,
    height: [String, Number],
    plugins: [String, Array],
    toolbar: [String, Array],
    menubar: [String, Array],
  },
  data() {
    return {
      id: this.uuid(),
      dataValue: "",
      languageTypeList: {
        en: "en",
        zh: "zh_CN",
        es: "es_MX",
        ja: "ja",
      },
      showInit: {},
    };
  },
  computed: {
    editor() {
      return window.tinymce.get(this.id);
    },

    showToolbar() {
      return this.toolbar != undefined ? this.toolbar : toolbar;
    },

    showPlugins() {
      return this.plugins != undefined ? this.plugins : plugins;
    },
  },
  watch: {
    value: {
      handler(val) {
        if (val != this.dataValue) {
          this.dataValue = val;
        }
      },
      immediate: true,
      deep: true,
    },
    dataValue() {
      this.$emit("input", this.dataValue);
    },
    init: {
      handler() {
        this.initTinymce();
      },
      immediate: true,
      deep: true,
    },
  },
  mounted() {
    setTimeout(() => {
      // this.insertContent();
      // console.log(this.dataValue);
    }, 2000);
  },
  methods: {
    insertContent() {
      // this.editor.insertContent(
      //   '<img class="qrcode" style="float: right;" src="{title}" alt="" width="79" height="79" />'
      // );
      console.log("this.editor", this.editor);
    },
    initTinymce() {
      const initDefault = {
        skin: "wukong",
        resize: false,
        branding: false,
        language: this.languageTypeList["zh"],
        menubar: this.menubar ? this.menubar : false,
        body_class: "panel-body",
        image_advtab: true,
        end_container_on_empty_block: true,
        powerpaste_word_import: "clean",
        // content_css: ['./static/tinymce/css/tiny-wukong.css'],
        fontsize_formats: "12px 14px 16px 18px 24px 36px 48px 56px 72px",
        font_formats:
          "Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats;微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif",
        code_dialog_height: 450,
        code_dialog_width: 1000,
        advlist_bullet_styles: "square",
        advlist_number_styles: "default",
        imagetools_cors_hosts: ["www.tinymce.com", "codepen.io"],
        default_link_target: "_blank",
        link_title: false,
        quickbars_insert_toolbar: false,
        nonbreaking_force_tab: true,
        convert_urls: false,

        ...this.init,
        //  toolbar_mode: "sliding",
        setup: (editor) => {
          // console.log("editor======>", editor);
          editor.ui.registry.addButton("myButton", {
            text: "二维码",
            icon: "select-all",
            onAction: () => {
              this.openqrcode();
            },
          });
          editor.ui.registry.addButton("myButton2", {
            text: "条形码",
            icon: "border-width",
            onAction: () => {
              this.openbarcode();
            },
          });
        },
      };

      /**
       * statusbar 隐藏底部状态栏
       */

      if (this.height != undefined) {
        initDefault.height = this.height;
      }
      this.showInit = initDefault;
    },
    uuid() {
      const time = Date.now();
      const random = Math.floor(Math.random() * 1000000000);

      unique++;

      return "wukong_" + random + unique + String(time);
    },
    openqrcode() {
      this.$prompt(
        "请输入绑定字段(如:{code},里层请加前缀如{T1.code})",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          inputPattern: /^[\s\S]*.*[^\s][\s\S]*$/,
          inputErrorMessage: "不能为空",
        }
      )
        .then(({ value }) => {
          this.setqrcode(value);
          // this.editor.insertContent(
          //   `<img class="qrcode" style="float: right;" src="${value}"  alt="" width="79" height="79" alt="二维码显示"/>`
          // );
        })
        .catch(() => {});
    },
    openbarcode() {
      this.$prompt(
        "请输入绑定字段(如:{code},里层请加前缀如{T1.code})",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          inputPattern: /^[\s\S]*.*[^\s][\s\S]*$/,
          inputErrorMessage: "不能为空",
        }
      )
        .then(({ value }) => {
          this.setbarcode(value);
          // this.editor.insertContent(
          //   `<img class="barcode" style="float: right;"src="${value}" alt="" width="133" height="40" alt="条形码维码显示"/>`
          // );
        })
        .catch(() => {});
    },

    setqrcode(v) {
      var that = this;
      var text = v;
      var div = document.createElement("div");
      let qrcode = new QRCode(div, {
        width: 265,
        height: 265, // 高度
        text: text, // 二维码内容

        correctLevel: QRCode.CorrectLevel.H, //容错级别 容错级别有：（1）QRCode.CorrectLevel.L （2）QRCode.CorrectLevel.M （3）QRCode.CorrectLevel.Q （4）QRCode.CorrectLevel.H
      });
      function getNowSrc() {
        setTimeout(() => {
          var nowSrc = div.getElementsByTagName("img")[0].getAttribute("src");
          if (nowSrc) {
            that.editor.insertContent(
              `<img class="qrcode" style="float: right;" src="${nowSrc}"    width="79" height="79" alt="${v}"/>`
            );
            div = null;
          } else {
            getNowSrc();
          }
        }, 50);
      }
      getNowSrc();
    },

    setbarcode(v) {
      var that = this;
      that.$refs.imgId.src = "";
      JsBarcode(`#ceshi`, v, {
        // format: "pharmacode",
        // lineColor: "#0aa",
        width: 4,
        height: 80,
        displayValue: false,
      });
      function getNowSrc() {
        setTimeout(() => {
          var nowSrc = that.$refs.imgId.getAttribute("src");
          if (nowSrc) {
            that.editor.insertContent(
              `<img class="barcode" style="float: right;" src="${nowSrc}"   width="133" height="40" alt="${v}"/>`
            );
            div = null;
          } else {
            getNowSrc();
          }
        }, 50);
      }
      getNowSrc();
    },
  },
};
</script>

<style lang="scss">
.tinymce-container {
  position: relative;
  line-height: normal;
}

.tinymce-container >>> .mce-fullscreen {
  z-index: 10000;
}

.tinymce-textarea {
  visibility: hidden;
  z-index: -1;
}

.tox-tinymce-aux {
  z-index: 10001 !important;
}

.tox .tox-toolbar,
.tox .tox-toolbar__overflow,
.tox .tox-toolbar__primary {
  background-color: #fff !important;
}
</style>
